package promote.brozen.dubbo.providers.api;

import org.apache.dubbo.config.annotation.DubboService;
import promote.brozen.dubbo.interfaces.api.UserApi;
import promote.brozen.dubbo.interfaces.beans.User;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author Brozen
 * @date 2020/9/2 3:05 PM
 * @email brozen@qq.com
 */
@DubboService(mock = "true", protocol = "30010")
public class UserApiProvider implements UserApi {

    private static AtomicLong ID_GENERATOR = new AtomicLong(0L);

    private static Map<Long, User> DB = new ConcurrentHashMap<>();


    @Override
    public void createUser(User user) {
        if (user.getUserId() != null) {
            if (DB.containsKey(user.getUserId())) {
                throw new IllegalArgumentException("Already Exist User!");
            }
        } else {
            user.setUserId(ID_GENERATOR.getAndIncrement());
        }

        DB.put(user.getUserId(), user);
    }

    @Override
    public User getUser(Long userId) {
        return DB.get(userId);
    }

    @Override
    public List<User> listUser() {
        return new ArrayList<>(DB.values());
    }
}
